package com.tanhua.manage.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.MovementsVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.PublishApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.omg.CORBA.StringHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private VideoApi videoApi;

    @Reference
    private PublishApi publishApi;

    @Reference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private final String FREEZE_KEY = "FREEZE_KEY_"; // 定义冻结状态的前缀

    /**
     * 接口名称：用户数据翻页
     */
    public ResponseEntity<Object> findByPage(Integer page, Integer pagesize) {
        // 调用服务提供者分页查询用户列表
        IPage<UserInfo> result = userInfoApi.findByPage(page, pagesize);

        // 封装返回结果
        PageResult pageResult = new PageResult(page, pagesize, (int) result.getTotal(), result.getRecords());

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 用户基本资料
     */
    public ResponseEntity<Object> findById(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 视频记录翻页
     */
    public ResponseEntity<Object> findVideosList(Long uid, Integer page, Integer pagesize) {
        // 1.调用服务提供者分页查询某用户的视频列表
        PageResult pageResult = videoApi.findVideosList(uid, page, pagesize);

        // 获取当前页的数据
        List<Video> videoList = (List<Video>) pageResult.getItems();

        // 2.封装返回结果
        List<VideoVo> voList = new ArrayList<>();
        if (videoList != null && videoList.size() > 0) {
            for (Video video : videoList) {
                // 2.1 创建vo
                VideoVo vo = new VideoVo();

                // 2.2 封装vo
                vo.setId(video.getId().toString());
                BeanUtils.copyProperties(video, vo);

                // 查询作者详情
                UserInfo userInfo = userInfoApi.findById(video.getUserId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                vo.setSignature(video.getText());
                vo.setCover(video.getPicUrl());

                // 2.3 添加vo
                voList.add(vo);
            }
        }
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：动态分页
     */
    public ResponseEntity<Object> findMovementsList(Integer page, Integer pagesize, Long uid, Long state) {

        PageResult pageResult = publishApi.queryMyPublishList(page, pagesize, uid);

        setMovementsVo(pageResult);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 封装结果数据公共方法
     */
    private void setMovementsVo(PageResult pageResult) {

        // 获取当前页的数据
        List<Publish> publishList = (List<Publish>) pageResult.getItems();

        // 3.封装返回结果
        List<MovementsVo> voList = new ArrayList<>();

        if (publishList != null && publishList.size() > 0) {
            for (Publish publish : publishList) {
                // 3.1 创建vo
                MovementsVo vo = new MovementsVo();

                // 3.2 封装数据
                // 封装动态信息
                BeanUtils.copyProperties(publish, vo);
                // 封装用户详情信息
                UserInfo userInfo = userInfoApi.findById(publish.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                    if (!StringUtils.isEmpty(userInfo.getTags())) {
                        String[] tags = userInfo.getTags().split(",");
                        vo.setTags(tags);
                    }
                }

                vo.setId(publish.getId().toString());
                if (publish.getMedias() != null) {
                    String[] medias = publish.getMedias().toArray(new String[]{});
                    vo.setImageContent(medias);
                }

                vo.setDistance("50米");
                // 格式化日期
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(new Date(publish.getCreated())));

                // 3.3 添加vo到voList
                voList.add(vo);
            }
        }

        // 4.重新设置pageResult中的items
        pageResult.setItems(voList);
    }

    /**
     * 接口名称：动态详情
     */
    public ResponseEntity<Object> findMovementsById(String publishId) {
        // 1.调用服务提供者api查询动态详情
        Publish publish = publishApi.findById(publishId);

        // 2.封装返回数据
        MovementsVo vo = new MovementsVo();

        // 封装数据
        // 封装动态信息
        BeanUtils.copyProperties(publish, vo);

        // 封装用户详情信息
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            if (!StringUtils.isEmpty(userInfo.getTags())) {
                String[] tags = userInfo.getTags().split(",");
                vo.setTags(tags);
            }
        }

        vo.setId(publish.getId().toString());
        if (publish.getMedias() != null) {
            String[] medias = publish.getMedias().toArray(new String[]{});
            vo.setImageContent(medias);
        }

        vo.setDistance("50米");
        // 格式化日期
        vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date(publish.getCreated())));

        return ResponseEntity.ok(vo);
    }

    /**
     * 接口名称：评论列表翻页
     */
    public ResponseEntity<Object> findCommentsById(String publishId, Integer page, Integer pagesize) {
        // 1.调用服务提供者api，根据动态id查询评论列表，并分页
        PageResult pageResult = commentApi.queryCommentsList(publishId, page, pagesize);

        // 获取当前页的数据
        List<Comment> commentList = (List<Comment>) pageResult.getItems();

        // 2.封装返回数据
        List<CommentVo> voList = new ArrayList<>();
        if (commentList != null && commentList.size() > 0) {
            for (Comment comment : commentList) {
                // 2.1 创建vo
                CommentVo vo = new CommentVo();

                // 2.2 封装vo
                vo.setId(comment.getId().toString());

                // 查询评论人的详情
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                vo.setContent(comment.getContent());
                // 日期格式化
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(comment.getCreated())));
                vo.setLikeCount(comment.getLikeCount());
                vo.setHasLiked(0);

                // 2.3 添加vo到集合
                voList.add(vo);
            }
        }

        // 3.重新设置items的值
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：用户冻结操作
     */
    public ResponseEntity<Object> freeze(Map<String, Object> param) {

        Integer userId = (Integer) param.get("userId");
        String freezingTime = (String) param.get("freezingTime"); //冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
        String freezingRange = (String) param.get("freezingRange"); //冻结范围，1为冻结登录，2为冻结发言，3为冻结发布动态
        String reasonsForFreezing = (String) param.get("reasonsForFreezing"); //冻结原因
        String frozenRemarks = (String) param.get("frozenRemarks"); //冻结备注

        UserInfo userInfo = userInfoApi.findById(userId.longValue());

        userInfo.setUserStatus("2");
        userInfo.setFreezingTime(freezingTime);
        userInfo.setFreezingRange(freezingRange);

        userInfoApi.update(userInfo);


        int days = 0;
        if ("1".equals(freezingTime)) {
            days = 3;
        } else if ("2".equals(freezingTime)) {
            days = 7;
        } else if ("3".equals(freezingTime)) {
            days = 999999999;
        }

        redisTemplate.opsForValue().set(FREEZE_KEY + userId , freezingRange,Duration.ofDays(days));

        Map<String,String> result = new HashMap<>();
        result.put("冻结操作","操作成功");

        return ResponseEntity.ok(result);

    }



    /**
     * 接口名称：用户解冻操作
     */
    public ResponseEntity<Object> unfreeze(Map<String, Object> param) {

        Integer userId = (Integer) param.get("userId");
        String reasonsForThawing = (String) param.get("reasonsForThawing");

        UserInfo userInfo = userInfoApi.findById(Long.valueOf(userId));
        userInfo.setUserStatus("1");
        userInfo.setFreezingTime("0");
        userInfo.setFreezingRange("0");

        userInfoApi.update(userInfo);

        redisTemplate.delete(FREEZE_KEY + userId);

        Map<String,String> result = new HashMap<>();
        result.put("解冻操作","操作成功");

        return ResponseEntity.ok(result);


    }



}
